import axios from 'axios';
import wx from 'weixin-js-sdk';

const _cookieKey = {
  weixin_oauthUserInfo: '_k1',
  weixin_jsSdkSignature: '_k2',
  oauth2_run_count: '_k3',
}
const _requestUrl = {
  oauth2WXCommonJS: '/WXCommonJS/Index',
  getJsSdkUiPackage: '/WXCommonJS/GetJsSdkUiPackage'
}

const xtyCookie = {
  get: function (n) {
    var re = new RegExp(n + '=([^;]*);?', 'gi');
    var r = re.exec(document.cookie) || [];
    var data = r.length > 1 ? r[1] : null;
    if (data != null) {
      return JSON.parse(decodeURIComponent(data));
    }
    return false;
  },
  set: function (n, v, e, p, d, s) {
    var t = new Date;
    if (e) {
      t.setTime(t.getTime() + (e * 8.64e7));
    }
    document.cookie = n + '=' + encodeURIComponent(JSON.stringify(v)) + '; ' + (!e ? '' : '; expires=' + t.toGMTString()) + (!p ? '' : '; path=' + p) + (!d ? '' : '; domain=' + d) + (!s ? '' : '; secure')
  },
  remove: function (n, p, d) {
    var t = xtyCookie.get(n);
    document.cookie = n + '=' + (!p ? '' : '; path=' + p) + (!d ? '' : '; domain=' + d) + '; expires=Thu, 01-Jan-70 00:00:01 GMT';
    return t
  }
};

function isWeixin() {
  return navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == "micromessenger" &&
    window.location.href.indexOf("https://weixin.zhujia100.com") > -1
}

function ajaxGetJsSdkUiPackage(url) {
  return axios.post(_requestUrl.getJsSdkUiPackage, {
    url
  }).then(res=>res.data)
}

export default {
  shareWeixin: function (config) {
    wx.onMenuShareTimeline(config);
    wx.onMenuShareAppMessage(config);
  },
  jsSdkSignatureReady: (readyCallback, errorCallback, extra) => {
    var url = window.location.href;
    ajaxGetJsSdkUiPackage(url).then(data => {
      console.log('data',data)
      xtyCookie.set(_cookieKey.weixin_jsSdkSignature, data)
      wx.config({
        debug: false,
        appId: data.AppId,
        timestamp: data.Timestamp,
        nonceStr: data.NonceStr,
        signature: data.Signature,
        jsApiList: [
          'onMenuShareTimeline',
          'onMenuShareAppMessage'
        ]
      });
      wx.error(e => {
        console.log(e)
        if (typeof (errorCallback) == "function")
          errorCallback(e);
      })
      wx.ready(function () {
        if (typeof (readyCallback) == "function")
          readyCallback(data, extra);
      });
    })
  },
  weixinLogin: () => {
    if (isWeixin()) {
      console.log('isWeixin')
      const userinfo = xtyCookie.get(_cookieKey.weixin_oauthUserInfo);
      if (!userinfo) {
        // 后端处理验证，并在后端写入 weixin_oauthUserInfo 的 cookie 值
        window.location.replace(_requestUrl.oauth2WXCommonJS + '?returnUrl=' + encodeURIComponent(window.location.href))
      } else {
        return userinfo
      }
    }
  },
  isIOS: () => {
    return (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent))
  }
}